#!/usr/bin/env python
# Copyright (c) 2014 Eugene Frolov <efrolov@mirantis.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
import sys

from oslo.config import cfg
import mimetypes
from restalchemy.api import middlewares
import webob

from rdb.old_app import kernel
from rdb.old_app.web_api import reports
from rdb.old_app.web_api import spare_parts


gui_opts = [
    cfg.StrOpt('static_files_path', default='/var/www/rdb-gui/',
               help="A path to GUI interface")
]

CONF = cfg.CONF
CONF.register_cli_opts(gui_opts, "gui")


def get_mimetype(filename):
    type, encoding = mimetypes.guess_type(filename)
    # We'll ignore encoding, even though we shouldn't really
    return type or 'application/octet-stream'


class StaticFilesMiddleware(middlewares.Middleware):

    def is_virtualenv(self):
        if hasattr(sys, 'real_prefix'):
            return True
        return False

    def get_prefix_path(self):
        if self.is_virtualenv():
            return sys.prefix
        return u'/'

    def get_full_path(self, path):
        return os.path.join(self.get_prefix_path(),
                            CONF.gui.static_files_path[1:],
                            path[1:])

    def make_response(self, path):
        response = webob.Response(content_type=get_mimetype(path))
        response.body = open(path, 'rb').read()
        return response

    def process_request(self, req):
        path = '/index.html' if req.path == '/' else req.path

        full_path = self.get_full_path(path)
        if os.path.exists(req.path):
            return self.make_response(req.path)
        if os.path.exists(full_path):
            return self.make_response(full_path)


def calculate_params(webob_params):
    result = {}
    for key, value in webob_params.iteritems():
        if key in result.keys():
            if not isinstance(result[key], list):
                result[key] = [result[key]]
            result[key].append(value)
        else:
            result[key] = value
    return result


def harcoded_mimetype(htype):
    if htype == "HTML":
        return "text/html"
    elif htype == "XML":
        return "text/xml"
    elif htype == "CSV":
        return "text/csv"


def get_param_safe(opts):
    return opts['param'] if 'param' in opts else []


class APIv2Support(middlewares.Middleware):

    def process_request(self, req):
        params = calculate_params(req.params)
        method = os.path.split(req.path)[1]
        if req.path.startswith('/bin/web_api/spare_parts.py'):
            result = getattr(spare_parts, method)(req, **params)
            if not hasattr(result, 'json'):
                return result
            return result.json()
        elif req.path.startswith('/bin/web_api/reports.py'):
            result = getattr(reports, method)(req, **params)
            if not hasattr(result, 'json'):
                return result
            return result.json()
        elif req.path.startswith('/bin/kernel.py'):
            method_opts = kernel.funcOpt[req.params['func']]
            params = {}
            for param in get_param_safe(method_opts):
                params[param] = req.params[param]

            response = webob.Response(
                content_type=harcoded_mimetype(method_opts['format']))
            response.body = str(method_opts['funcName'](**params))
            return response
